<template>
  <!-- onemap -->
  <div :class="['checkmaps ',start_draw_status==true?'draw':'']"
    style="display: flex;height: 100%;min-width: 1446px;position: relative;overflow: hidden;">
    <div class="mapDivs" id="mapDivs" style="width: calc(100% - 400px);">              
      <div id="mapDiv1">
        <div class="standard-map__mouse-position"
          style="color: #0c0c0c;background-color: white;font-size: 16px;right: 10px;left: auto;">
        </div>
        <div class="message-bar" >
          <a-space ref="tools" size="small">
            <span class="tiam-span">{{title}}</span>
          </a-space>
        </div>
      </div>
    </div>
    <div id="task4" style="border: 2px solid gray;width: 400px;">
      <a-row  >
        
      </a-row>
      <a-row style="text-align: center;">
        <a-col :span="3">
          名称:
        </a-col>
        <a-col :span="16">
          <a-input v-model:value="name" />
        </a-col>
        <a-col :span="1">

        </a-col>
        <a-col :span="4">
          <a-button type="primary" size="small" @click="GetWMTS">查询</a-button>
        </a-col>
      </a-row>
      <a-row  class="empty wmts" style="user-select: text;">
        <!-- style="user-select: text;" -->
        <a-table :columns="layer_table_columns" 
        :data-source="wmts_layers" 
        bordered 
        :pagination="layer_pagination"  
        size="small"
        @change="layer_change_pagination"
        :customRow="layer_row_event"
        :showHeader="false"
        rowKey="Title"
        >
          <span slot="actionstatus" slot-scope="text, record" :class="['eyes',get_record_Visible(record)==true?'show':'hide']">
            <a-icon type="eye"  @click="eye_click(record)"/>
          </span>
        </a-table>
      </a-row>
    </div>
  </div>
</template>
<script>
const xml2js = require('xml2js');
  export default {
    data() {
      return {
        wmts_layers:[],
        active_layer: {},
        name:"",
        wmts_url:"https://nmgwxyy.cn/alatan/services/ogc/wmts?",
        // wmts_url:"http://172.16.104.120:8052/ogc/wmts?",
        title:"",
        layer_table_columns:[
          {
            title: '服务名',
            dataIndex: 'Title',
            width:130,
            align:'center',
            ellipsis:true,

          },
          {
            title: '操作',
            width:20,
            scopedSlots: { customRender: 'actionstatus' },
            align:'center'
          },
        ],
        
        layer_pagination:{
          size:'small',
          pageSize:10,
          total:0,
          current:1,
          showTotal:(total, range)=>{
              return `${total}个，${range[0]}-${range[1]}`
          },
          // showSizeChanger:true,
          // pageSizeOptions:['10'],
        },
        layer_row_event: record => ({
          on: {
            dblclick: () => {
              this.eye_click(record)
            },
          },
        }),
        ol_map: null,
      }
    },
    components: {
      draw_end_check: () => import('./draw_end_check.vue'),
    },
    mounted() {
      setTimeout(() => {
        this.InitMap([])
        this.GetWMTS();
      }, 500);
    },
    methods: {
      init_map(){
        this.InitMap([])
      },
      async GetWMTS(){
        this.wmts_layers=[]
        let from=(this.layer_pagination.current-1)*this.layer_pagination.pageSize+1
        let size=this.layer_pagination.pageSize
        let result=await this.Get_wmts_by_from_size(this.name,from,size)
        this.wmts_layers=result
        this.$forceUpdate()
      },


      

      
      async  Load_xml(_xmlString){
        try{
          let xmlParser =new xml2js.Parser({
            explicitArray:false, 
            ignoreAttrs : true
          });
          return await xmlParser.parseStringPromise(_xmlString)
        }
        catch(err){
          return undefined
        }
      },
      Get_wmts_Capabilities(_layer_name){
        return fetch(`${this.wmts_url}Service=WMTS&Request=GetCapabilities&layer=${_layer_name}`).then((response)=> {
          if(response.status === 200){
            return response.text();
          }else{
            return {}
          }
        });
      },
      async Get_wmts_by_from_size(layer,from,size){
        let data=await fetch(`${this.wmts_url}from=${from}&size=${size}&layer=${layer}`).then((response)=> {
          if(response.status === 200){
            return response.text();
          }else{
            return {}
          }
        });
        let json_data=await this.Load_xml(data)
        let GetCapabilities_Layer=json_data?.Capabilities?.Contents?.Layer
        if(!GetCapabilities_Layer.length){
          GetCapabilities_Layer=[GetCapabilities_Layer]
        }
        let layers=[]
        for (let index = 0; index < GetCapabilities_Layer.length; index++) {
          this.layer_pagination.total=GetCapabilities_Layer[index]["ows:Count"]-0
          layers.push({
            Title:GetCapabilities_Layer[index]["ows:Title"],
            vised:"hide",
            props:{}
          })
        }
        return layers
      },
      async GetCapabilities(one_layer_name){
        let layer_props={}
        let data=await this.Get_wmts_Capabilities(one_layer_name)
        let json_data=await this.Load_xml(data)
        let GetCapabilities_Layer=json_data?.Capabilities?.Contents?.Layer
        if(!GetCapabilities_Layer.length){
          GetCapabilities_Layer=[GetCapabilities_Layer]
        }
        let find_index=GetCapabilities_Layer.findIndex((val)=>{
          let Identifier=val["ows:Identifier"]
          return Identifier==one_layer_name
        })
        if(find_index>=0){
          layer_props.title=GetCapabilities_Layer[find_index]["ows:Title"]
          layer_props.center=this.get_layer_center(GetCapabilities_Layer[find_index]["ows:WGS84BoundingBox"])
          let Style=GetCapabilities_Layer[find_index]["Style"]["ows:Identifier"]
          let tilematrixset=GetCapabilities_Layer[find_index]["TileMatrixSetLink"]["TileMatrixSet"]
          layer_props.wmts=`${this.wmts_url}layer=${one_layer_name}&style=${Style}&tilematrixset=${tilematrixset}&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/png&TileMatrix={z}&TileCol={x}&TileRow={y}`
          layer_props.group=[
            this.ol_mapClass.GetTileLayer(layer_props.wmts,{
              projection: 'EPSG:4326',
            })
          ]
          
          
          // new ol.layer.Group({
          //   layers:[
          //     this.ol_mapClass.GetTileLayer(layer_props.wmts,{
          //       projection: 'EPSG:4326',
          //       // tileLoadFunction:async function(imageTile, src) {
          //       //   fetch(src).then((response) => response.blob()).then((response) => {
          //       //     const reader = new FileReader();
          //       //     reader.readAsDataURL(response);
          //       //     reader.onload = () =>{
          //       //       //console.log(reader.result)
          //       //       imageTile.getImage().src =reader.result
          //       //     };
          //       //     reader.onerror = (error) => reject(error);
          //       //   });   
          //       // }
          //     }),
          //     // new ol.layer.Tile({
          //     //   source: new ol.source.XYZ({
          //     //     projection:"EPSG:4326",
          //     //     url:`https://nmgwxyy.cn/alatan/services2/ogc/wmts?layer=tianditu_cia_c&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix={z}&TileCol={y}&TileRow={x}`
          //     //   }),
          //     // }),
          //   ],
          //   visible:true,
          // })
        }
        return layer_props
      },
      async GetCapabilities3(wmts_layers){
        let wmts_url=""
        let layers=[]
        for (let index = 0; index < wmts_layers.length; index++) {
          let one_layer = wmts_layers[index];
          wmts_layers[index].key=index
          wmts_layers[index].vised="hide"
          wmts_layers[index].props={}
          let one_layer_name=one_layer.layer
          let data=await this.Get_wmts_Capabilities(wmts_url,one_layer_name)
          let json_data=await this.Load_xml(data)
          let GetCapabilities_Layer=json_data?.Capabilities?.Contents?.Layer
          if(!GetCapabilities_Layer.length){
            GetCapabilities_Layer=[GetCapabilities_Layer]
          }
          let find_index=GetCapabilities_Layer.findIndex((val)=>{
            let Identifier=val["ows:Identifier"]
            return Identifier==one_layer_name
          })
          if(find_index>=0){
            one_layer.props.title=GetCapabilities_Layer[find_index]["ows:Title"]
            one_layer.props.center=this.get_layer_center(GetCapabilities_Layer[find_index]["ows:WGS84BoundingBox"])
            let Style=GetCapabilities_Layer[find_index]["Style"]["ows:Identifier"]
            let tilematrixset=GetCapabilities_Layer[find_index]["TileMatrixSetLink"]["TileMatrixSet"]
            // EPSG:4326:
            one_layer.props.wmts=`${wmts_url}layer=${one_layer_name}&style=${Style}&tilematrixset=${tilematrixset}&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/png&TileMatrix={z}&TileCol={x}&TileRow={y}`
            one_layer.props.group=new ol.layer.Group({
              layers:[
                this.ol_mapClass.GetTileLayer(one_layer.props.wmts,{
                  projection: 'EPSG:4326',
                  // tileLoadFunction:async function(imageTile, src) {
                  //   fetch(src).then((response) => response.blob()).then((response) => {
                  //     const reader = new FileReader();
                  //     reader.readAsDataURL(response);
                  //     reader.onload = () =>{
                  //       //console.log(reader.result)
                  //       imageTile.getImage().src =reader.result
                  //     };
                  //     reader.onerror = (error) => reject(error);
                  //   });   
                  // }
                }),
                // new ol.layer.Tile({
                //   source: new ol.source.XYZ({
                //     projection:"EPSG:4326",
                //     url:`https://nmgwxyy.cn/alatan/services2/ogc/wmts?layer=tianditu_cia_c&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix={z}&TileCol={y}&TileRow={x}`
                //   }),
                // }),
              ],
              visible:false,
            })
            layers.push(one_layer.props.group)
          }
        }
        this.InitMap(layers)
        // if(wmts_layers.length>0){
        //   this.update_Map_center(wmts_layers[0].props.center)
        //   wmts_layers[0].props.group.setVisible(true);
        //   wmts_layers[0].vised="show"
        //   this.title=wmts_layers[0].layer
        // }
        this.wmts_layers=wmts_layers
        this.$forceUpdate()
      },
      async GetCapabilities2(wmts_layers){
        // let wmts_url="http://172.16.104.120:8051/ogc/wmts?"
        // &layer=GF701_0065_04289930_20230428112615_000BWD_003_S
        // let promise = fetch(`${wmts_url}Service=WMTS&Request=GetCapabilities`).then((response)=> {
        
        let promise = fetch(`${wmts_url}Service=WMTS&Request=GetCapabilities`).then((response)=> {
          if(response.status === 200){
            return response.text();
          }else{
            return {}
          }
        });
        let data=await promise
        let json_data=await this.Load_xml(data)
        let GetCapabilities_Layer=json_data?.Capabilities?.Contents?.Layer
        if(!GetCapabilities_Layer.length){
          GetCapabilities_Layer=[GetCapabilities_Layer]
        }
        let layers=[]
        for (let index = 0; index < wmts_layers.length; index++) {
          let one_layer = wmts_layers[index];
          wmts_layers[index].key=index
          wmts_layers[index].vised="hide"
          wmts_layers[index].props={}
          let one_layer_name=one_layer.layer
          let find_index=GetCapabilities_Layer.findIndex((val)=>{
            let Identifier=val["ows:Identifier"]
            return Identifier==one_layer_name
          })
          if(find_index>=0){
            one_layer.props.title=GetCapabilities_Layer[find_index]["ows:Title"]
            one_layer.props.center=this.get_layer_center(GetCapabilities_Layer[find_index]["ows:WGS84BoundingBox"])

            let Style=GetCapabilities_Layer[find_index]["Style"]["ows:Identifier"]
            let tilematrixset=GetCapabilities_Layer[find_index]["TileMatrixSetLink"]["TileMatrixSet"]
            // EPSG:4326:
            one_layer.props.wmts=`${wmts_url}layer=${one_layer_name}&style=${Style}&tilematrixset=${tilematrixset}&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/png&TileMatrix={z}&TileCol={x}&TileRow={y}`
            one_layer.props.group=new ol.layer.Group({
              layers:[
                this.ol_mapClass.GetTileLayer(one_layer.props.wmts,{
                  projection: 'EPSG:4326',
                  tileLoadFunction:async function(imageTile, src) {
                    // imageTile.getImage().src = src;
                    fetch(src).then((response) => response.blob()).then((response) => {
                      const reader = new FileReader();
                      reader.readAsDataURL(response);
                      reader.onload = () =>{
                        //console.log(reader.result)
                        imageTile.getImage().src =reader.result
                      };
                      reader.onerror = (error) => reject(error);
                    });   
                  }
                }),
                new ol.layer.Tile({
                  source: new ol.source.XYZ({
                    projection:"EPSG:4326",
                    url:`https://nmgwxyy.cn/alatan/services/ogc/wmts?layer=tianditu_cia_c&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix={z}&TileCol={y}&TileRow={x}`
                  }),
                }),
              ],
              visible:false,
            })
            layers.push(one_layer.props.group)
          }
        }
        this.InitMap(layers)
        // if(wmts_layers.length>0){
        //   this.update_Map_center(wmts_layers[0].props.center)
        //   wmts_layers[0].props.group.setVisible(true);
        //   wmts_layers[0].vised="show"
        //   this.title=wmts_layers[0].layer
        // }
        this.wmts_layers=wmts_layers
        this.$forceUpdate()
      },
      get_layer_center(obj){
        let LowerCorner=obj["ows:LowerCorner"]
        let UpperCorner=obj["ows:UpperCorner"]
        let LowerCorners=LowerCorner.split(" ")
        let UpperCorners=UpperCorner.split(" ")
        let X_center=((LowerCorners[0]-0)+(UpperCorners[0]-0))/2
        let Y_center=((LowerCorners[1]-0)+(UpperCorners[1]-0))/2
        return [X_center,Y_center]
      },
      get_record_Visible(record){
        let Visible=false
        if(record?.vised=="show"){
          Visible=true
        }
        return Visible
      },
      layer_change_pagination(pagination){
        this.layer_pagination.current=pagination.current
        if(pagination.pageSize!=this.layer_pagination.pageSize){
          this.layer_pagination.pageSize=pagination.pageSize
          this.layer_pagination.current=1
        }
        this.GetWMTS()
      },
      async eye_click(record){
        let old_show=record.vised
        for (let index = 0; index < this.wmts_layers.length; index++) {
          try{
            // this.wmts_layers[index].props.group.setVisible(false);
            this.wmts_layers[index].vised="hide"
          }
          catch(error){
            console.log(error.message)
          }
        }
        if(old_show=="hide"){
          let layer_props=await this.GetCapabilities(record.Title)
          this.ol_map.update_layer(layer_props.group,1)
          this.update_Map_center(layer_props.center)
          // record.props.group.setVisible(true);
          record.vised="show"
          this.title=record.Title
        }
        else{
          this.ol_map.update_layer([],1)
          this.title=""
        }
        this.$forceUpdate()
      },
      InitMap(layers) {
        if (!this.ol_map) {
          this.ol_map = new this.ol_mapClass({
            center: [0,0],
            target1: 'mapDiv1',
            zoom: 10,
            layers1: layers,
          })
          this.ol_map.upDate()
        }
      },
      update_Map_center(center) {
        if (this.ol_map) {
          this.ol_map.update_center(center)
        }
      },
    },
    beforeDestroy() {
      document.onkeydown = undefined
    },
  }
</script>
<style>
.eyes.show{
  color: #377ee8;
}
  .checkmaps .mapDivs {
    width: calc(100% - 300px);
    height: 100%;
    position: relative;
    display: flex;
  }

  #task4 {
    width: 300px;
    height: 100%
  }

  .mapDivs #mapDiv1,
  .mapDivs #mapDiv2 {
    width: calc(100% - 0px);
  }

  .standard-map__map-tool {
    position: absolute;
    top: 8px;
    right: 8px;
    z-index: 10;
  }

  .map-tools__item {
    display: inline-block;
    cursor: pointer;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    -webkit-box-shadow: rgb(0 0 0 / 25%) 0 0 4px 0;
    box-shadow: 0 0 4px 0 rgb(0 0 0 / 25%);
    margin: 0 2px;
    padding: 1px;
    background: hsla(0, 0%, 100%, .92);
    border-radius: 4px;
  }

  .map-tools__item svg {
    height: 28px;
    width: 28px;
  }

  .draw #mapDiv1 {
    /* zoom: 0.5; */
    width: 401px;
    height: 401px;
    position: absolute;
    z-index: 1;
  }

  .draw #mapDiv2 {
    width: 100%;
  }

  .standard-map__mouse-position {
    position: absolute;
    bottom: 8px;
    left: 10px;
    font-size: 12px;
    z-index: 3;
    color: #000000;
    background-color: white;
  }

  #line {
    width: 4px;
    height: 100%;
    position: absolute;
    top: 0;
    left: calc(50% - 5px);
    background-color: #1890ff;
    border: 1px solid #1890ff;
    z-index: 2;
    cursor: pointer;
  }
  .line-ico {
    position: absolute;
    top: 50%;;
    left: -10px;
    width: 24px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    border-radius: 100%;
    color: #fff;
    border: 1px solid #5883f4;
    background-color: #5883f4;
}
.wmts .ant-table-row-cell-break-word{
  font-size: 10px;
}
</style> 